﻿package net.wangit.framework.util;

import net.wangit.MapList;
import net.wangit.util.Checker;
import net.wangit.util.EmptyObject;
import net.wangit.util.StringUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class MapListUtil {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.util.MapListUtil.class);

	public MapListUtil() {
	}

	public static String[] getArray(MapList list, String name) {
		if (!Checker.isEmpty(list)) {
			String groups[] = new String[list.size()];
			for (int i = 0; i < list.size(); i++)
				groups[i] = list.getRow(i).get(name);

			return groups;
		} else {
			return EmptyObject.STRING_ARRAY;
		}
	}

	public static MapList getMapList(String expression) {
		expression = StringUtil.replace(expression, "\n", "");
		MapList result = new MapList();
		String points[] = StringUtil.split(expression, ";");
		for (int i = 0; i < points.length; i++) {
			String props[] = StringUtil.split(points[i], ",");
			for (int j = 0; j < props.length; j++) {
				String prop[] = props[j].split("=");
				if (prop.length > 1)
					result.put(i, prop[0].trim(), prop[1].trim());
			}

		}

		return result;
	}

	public static MapList getEnumeration(String expression) {
		if (Checker.isEmpty(expression))
			return null;
		MapList result;
		result = new MapList();
		try {
			String list[][] = StringUtil.split(expression, ";", ",");
			for (int i = 0; i < list.length; i++) {
				String row[] = list[i];
				result.put(i, "value", row[0]);
				result.put(i, "name", row[1]);
			}

			return result;
		} catch (Exception e) {
			if (log.isWarnEnabled())
				log.warn((new StringBuilder("expression is invalid : "))
						.append(expression).toString());
			return null;
		}
	}

}
